package com.bw.lib_check_wdy_xin.listview

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.CheckBox
import android.widget.TextView
import com.bw.lib_check_wdy_xin.R

class CheckboxListAdapter(private val items : List<CheckboxItem>,
    private val onItemCheckedChange : (Int,Boolean) -> Unit) : BaseAdapter() {
    override fun getCount(): Int = items.size

    override fun getItem(p0: Int): Any = items[p0]

    override fun getItemId(p0: Int): Long = p0.toLong()

    override fun getView(p0: Int, p1: View?, p2: ViewGroup?): View {
        val view = p1 ?: LayoutInflater.from(p2?.context)
            .inflate(R.layout.item_checkbox,p2,false)

        val item_box_wdy = view.findViewById<CheckBox>(R.id.item_box_wdy)
        val item_tv_wdy = view.findViewById<TextView>(R.id.item_tv_wdy)

        val item = items[p0]

        item_box_wdy.setOnCheckedChangeListener(null)

        item_box_wdy.isChecked = item.isChecked
        item_tv_wdy.text = item.text

        item_box_wdy.setOnCheckedChangeListener { _, b ->
            item.isChecked = b
            onItemCheckedChange(p0,b)
        }

        return view
    }

    fun updataAllItems(checked : Boolean){
        items.forEach {
            it.isChecked = checked
            notifyDataSetChanged()
        }
    }
}